package com.ad_hccm.controller;

import com.ad_hccm.domain.PatientUser;
import com.ad_hccm.domain.User;
import com.ad_hccm.exception.BusinessException;
import com.ad_hccm.interceptor.TokenUtil;
import com.ad_hccm.service.PatientUserService;
import com.ad_hccm.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * TODO 患者信息Controller
 */
@RestController
@RequestMapping("/patient_user")
public class PatientUserController {
    @Autowired
    private PatientUserService patientUserService;
    @Autowired
    TokenUtil tokenUtil;
    @Autowired
    private UserService userService;

    @PostMapping
    public Result save(@RequestBody PatientUser patientUser,HttpServletRequest request){
        String token = request.getHeader("token");
        Map<String,String> map = tokenUtil.parseToken(token);
        String userId = map.get("userId");
        User user = userService.getByAccount(userId);
        patientUser.setDoctorId(user.getId());
        boolean flag = patientUserService.save(patientUser);
        String msg = flag ? "添加失败" : "添加成功" ;
        return new Result( flag ? Code.SAVE_OK : Code.SAVE_ERR, flag, msg);
    }

    @PutMapping
    public Result update(@RequestBody PatientUser patientUser) {
        boolean flag = patientUserService.update(patientUser);
        String msg = flag ? "修改成功" : "数据修改失败，请重试";
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR , flag , msg);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable String id) {
        if(id.length()!=18) throw new BusinessException(Code.GET_ERR, "请输入18位的身份证");
        PatientUser patientUser = patientUserService.getById(id);
        Integer code = patientUser != null ? Code.GET_OK : Code.GET_ERR;
        String msg = patientUser != null ? "查询成功" : "没有该信息";
        return new Result(code , patientUser , msg);
    }

    @GetMapping
    public Result getAll(HttpServletRequest request) {
        String token = request.getHeader("token");
        Map<String,String> map = tokenUtil.parseToken(token);
        String userId = map.get("userId");
        User domain = userService.getByAccount(userId);
        List<PatientUser> patientUserList = patientUserService.getAll(domain.getId());
        Integer code = patientUserList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = patientUserList != null ? "查询成功" : "数据查询失败，请重试";
        return new Result(code , patientUserList , msg);
    }
}
